package com.orange.controller.demo;

import com.orange.common.annotation.PassToken;
import com.orange.common.base.controller.impl.BaseControllerImpl;
import com.orange.common.validation.Groups;
import com.orange.framework.result.R;
import com.orange.framework.wrapper.CachedBodyHttpServletRequest;
import com.orange.project.demo.pojo.UserPo;
import com.orange.project.demo.pojo.UserReq;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Optional;
import java.util.Set;

/**
 * 各种案例
 *
 * @Author YWF
 * @Date 2025/5/23 17:02
 */
@Validated
@RestController
@RequestMapping("/demo/")
public class ValidController extends BaseControllerImpl {

    @Autowired
    private Validator validator;

    /**
     * Body参数校验
     *
     * @param userReq
     * @return
     */
    @PassToken
    @PostMapping(value = "/saveUser")
    public R saveUser(@RequestBody @Validated(Groups.Create.class) UserReq userReq, CachedBodyHttpServletRequest cacheRequest) {
        UserReq rs = cacheRequest.getBodyAsJson(UserReq.class);
        logger.info("结果1：{}", rs.toString());
        logger.info("结果2：{}", cacheRequest.getBodyAsString());
        return R.ok().data(userReq);
    }

    /**
     * 编程式校验数据
     * 校验成功或失败可以执行不同的业务逻辑
     *
     * @param userReq
     * @return
     */
    @PostMapping(value = "/updateUser")
    public R updateUser(@RequestBody UserReq userReq) {
        Set<ConstraintViolation<UserReq>> validate = validator.validate(userReq, Groups.Update.class);
        if (validate.isEmpty()) {
            logger.info("校验通过，执行业务逻辑");
        } else {
            logger.info("校验失败，执行异常业务逻辑");
        }
        return R.ok().data(userReq);
    }

    @GetMapping(value = "getUsers")
    public R getUser(@RequestParam @Max(value = 99, message = "年龄不能大于99岁") Integer age,
                     @RequestParam @Min(value = 1, message = "页码必须大于0") Integer page,
                     @RequestParam @Range(min = 1, max = 100, message = "每页数量必须在1-100之间") Integer size,
                     CachedBodyHttpServletRequest cacheRequest) {
        logger.info("结果：{}", cacheRequest.getBodyAsString());
        UserPo user = new UserPo();
        user.setUserId(Optional.ofNullable(age).map(Integer::longValue).orElse(0L));
        return R.ok().data(user);
    }

}
